package com.caiyi.financial.nirvana.sms.cmpp20;

import com.caiyi.financial.nirvana.sms.cmpp20.message.CMPPMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * CMPP协议 数据流编码
 *
 * @author lvchaohua
 */
public class CMPPStreamEncoder extends MessageToByteEncoder<CMPPMessage> {

    //日志
    private final static Logger logger = LogManager.getLogger(CMPPStreamEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext context, CMPPMessage message, ByteBuf buff) throws Exception {
        try {
            //消息长度
            int size;
            size = message.encode(buff);

            //校正消息体长度
            message.setTotalLength(size);
            buff.setInt(0, size);
//			logger.debug("CMPP消息长度："+ size + " class == " + message.getCommandID());
//			if(message.getCommandID() == CMPPMessage.CMPP_CONNECT){
//				logger.error(ByteBufUtil.prettyHexDump(buff));
//			}
        } catch (Exception ex) {
            logger.error("channel:{}", context.channel());
            logger.error(ex.getMessage(), ex);
            logger.error("编码消息:" + message.toString());
            buff.clear();
//			logger.debug("ENCODE: " + ByteBufUtil.prettyHexDump(buff));
        }

    }
}
